//管理后台 状态
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getShoplist, getTypelist, addshoplist } from "../api/http";

let initialState = { //管理的状态
    shoplist: [], //存放商品列表数据
    typelist: [], //存放商品类型数据
    activeKey: '1'//分类切换的高亮
}

const crmsSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步修改状态的方法

        //获取商品列表
        getshoplist(state, action) {
            state.shoplist = action.payload
        },
        //获取商品类型
        gettypelist(state, action) {
            state.typelist = action.payload
        },
        //添加商品列表
        addshoplists(state, action) {
            state.shoplist.push(action.payload)
        },
        //编辑商品列表
        editshoplist(state, action) {
            //通过id找到这条数据 使用payload替换这条数据
            let index = state.shoplist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.shoplist[index] = action.payload
        },
        //删除商品
        delshoplist(state, action) {
            state.shoplist = state.shoplist.filter(item => {
                return item.id !== action.payload
            })
        },

        //切换高亮的方法
        changeactiveKey(state, action) {
            state.activeKey = action.payload
        },
        //添加商品类型数据
        addtypelists(state, action) {
            state.typelist.push(action.payload)
        },
        //删除商品分类 payload = key
        deltypelist(state, action) {
            state.typelist = state.typelist.filter(item => {
                return item.key !== action.payload
            })
        },

    },
});

export const {
    getshoplist, gettypelist, addshoplists, editshoplist,
    delshoplist, changeactiveKey, addtypelists,deltypelist
} = crmsSlice.actions;
export default crmsSlice.reducer;

//异步方法 获取商品列表
export let async_shoplist = createAsyncThunk('async_shoplist',
    async (_, store) => {
        //获取异步
        let res = await getShoplist()
        //同步修改异步
        store.dispatch(getshoplist(res))
    })
//获取商品类型
export let async_typelist = createAsyncThunk('async_typelist',
    async (_, store) => {
        //获取异步
        let res = await getTypelist()
        //同步修改异步
        store.dispatch(gettypelist(res))
    })
